package com.heatup.apt.api.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.heatup.apt.api.service.StoreService;
import com.heatup.apt.common.dao.CourseInfoMapper;
import com.heatup.apt.common.dao.OperativeMapper;
import com.heatup.apt.common.dao.ResourceMapper;
import com.heatup.apt.common.dao.ServicePriceMapper;
import com.heatup.apt.common.dao.coach.CoachInfoMapper;
import com.heatup.apt.common.dao.coach.CoachStarMapper;
import com.heatup.apt.common.dao.store.StoreInfoMapper;
import com.heatup.apt.common.dao.user.UserStoreMapper;
import com.heatup.apt.common.util.DateUtil;
import com.heatup.apt.model.Resource;
import com.heatup.apt.model.ResourceExample;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.api.ResourceModel;
import com.heatup.apt.model.api.store.StoreCoachModel;
import com.heatup.apt.model.api.store.StoreCourseModel;
import com.heatup.apt.model.api.store.StoreResourceModel;
import com.heatup.apt.model.api.store.StoreResultModel;
import com.heatup.apt.model.coach.CoachInfo;
import com.heatup.apt.model.coach.CoachStar;
import com.heatup.apt.model.course.CourseInfo;
import com.heatup.apt.model.management.InStore;
import com.heatup.apt.model.management.JsRSVideoInfo;
import com.heatup.apt.model.store.StoreInfo;

/**
 * Created by b3st9u on 16/8/21.
 */
@Service
public class StoreServiceImpl implements StoreService {
    protected static final Logger logger = LoggerFactory.getLogger(StoreServiceImpl.class);
    @Autowired
    StoreInfoMapper storeInfoMapper;

    @Autowired
    CoachInfoMapper coachInfoMapper;

    @Autowired
    ResourceMapper resourceMapper;

    @Autowired
    CourseInfoMapper courseInfoMapper;

    @Autowired
    ServicePriceMapper servicePriceMapper;
    @Autowired
    CoachStarMapper coachStarMapper;
    @Autowired
    OperativeMapper operativeMapper;
    
    @Autowired
	private UserStoreMapper userStoreMapper;

    /**
     * 根据门店ID查询门店详情
     * @param id
     * @return
     */
    @Override
    public StoreResultModel queryStoreByStoreId(int id) {
        StoreResultModel storeResultModel = null;
        StoreInfo storeInfo = storeInfoMapper.selectById(id);
        if (storeInfo != null) {
            storeResultModel = new StoreResultModel();
            //复制属性工具 可减少重复对象的获取和设值操作
            BeanUtils.copyProperties(storeInfo, storeResultModel);

            storeResultModel.setMobile(null);
            if (storeInfo.getIs24Hours() == null || (storeInfo.getIs24Hours() != null && storeInfo.getIs24Hours() == 2) ) {
                //非24小时营业门店才有开始结束时间
                storeResultModel.setOpenTime(DateUtil.formatDate(storeInfo.getOpenTime(), DateUtil.FMT_DATE_HHMM) + "~" + DateUtil.formatDate(storeInfo.getCloseTime(), DateUtil.FMT_DATE_HHMM));
            }
            String notice = storeInfo.getNotice();
            if (!Strings.isNullOrEmpty(notice)) {
                storeResultModel.setNotice(Arrays.asList(notice.split("\r\n")));  //文本框中的\r\n要换成数组传到前端
            }

            //modify by earvin 2017-2-28
//            if(storeInfo.getUserHasService()!=null){
//                storeResultModel.setUserHasService(storeInfo.getUserHasService());
//            }
//            if(storeInfo.getUserNotService()!=null){
//                storeResultModel.setUserNotService(storeInfo.getUserNotService());
//            }
//            if(storeInfo.getNapaStoreTips()!=null){
//            	storeResultModel.setNapaStoreTips(storeInfo.getNapaStoreTips());
//            }
//            storeResultModel.setManageType(storeInfo.getManageType());
            
            //教练信息
            storeResultModel.setCoaches(selectCoachesByStoreId(id));
            //查询店面banner图片
            storeResultModel.setImages(selectResourceByStoreId(id));
            //课程信息
            storeResultModel.setCourses(selectCourseInfoByStoreId(id));
            /*
            if (resources != null && resources.size() > 0) {
                List<ResourceModel> images = Lists.newArrayList();
                for (Resource resource : resources) {
                    ResourceModel resourceModel = new ResourceModel();
                    resourceModel.setId(resource.getId());
                    resourceModel.setLink(resource.getLink());
                    resourceModel.setTitle(resource.getPreviewUrl());
                    resourceModel.setTitle(resource.getTitle());
                    images.add(resourceModel);
                }
                storeResultModel.setImages(images);
            }*/

            //价格信息
//            ServicePriceExample servicePriceExample = new ServicePriceExample();
//            servicePriceExample.or().andStoreIdEqualTo(id);
//            List<ServicePrice> servicePrices = servicePriceMapper.selectByExample(servicePriceExample);
//            storeResultModel.setServicePrices(servicePrices);
        }
        return storeResultModel;
    }

    /**
     * 根据店面Id查询私教教练信息
     * @param storeId
     * @return
     */
    public List<StoreCoachModel> selectCoachesByStoreId(int storeId) {
//        List<CoachInfo> coachInfos = coachInfoMapper.selectCoachInfoByStoreId(storeId);
        //List<CoachInfo> coachInfoList = coachInfoMapper.selectSecretCoachInfoByStoreId(storeId);//现在只查询私教的教练 blank
    	Map<String,Object> paramsMap = new HashMap<>();
    	paramsMap.put("storeId", storeId);
    	List<CoachInfo> coachInfoList = coachInfoMapper.queryCoachPrivateListByStoreId(paramsMap);// 根据门店获取私教
    	List<StoreCoachModel> coachs = Lists.newArrayList();
        if (coachInfoList != null && coachInfoList.size() > 0) {
            for (CoachInfo coachInfo : coachInfoList) {
                StoreCoachModel storeCoachModel = new StoreCoachModel();
                //教练星级
                CoachStar coachStar = coachStarMapper.selectByCoachId(storeId);
                if (coachStar != null) {
                    storeCoachModel.setStar(coachStar.getStar());
                }
                storeCoachModel.setId(coachInfo.getId());
                storeCoachModel.setBriefing(coachInfo.getBriefing());
                storeCoachModel.setNickName(coachInfo.getNickName());
                storeCoachModel.setHeadImg(coachInfo.getHeadImg());
                storeCoachModel.setPersonalStatus(coachInfo.getPersonalStatus());
                String tags = coachInfo.getTags();
                if (!Strings.isNullOrEmpty(tags)) {
                    storeCoachModel.setTags(Arrays.asList(tags.split("#")));
                }
                if(StringUtils.isNotBlank(coachInfo.getGoodCourse())){
                    storeCoachModel.setGoodCourse(Arrays.asList(coachInfo.getGoodCourse().split("#")));
                }
                coachs.add(storeCoachModel);
            }
        }
        return coachs;
    }

    /**
     * 根据店面id查询图片视频等信息
     *
     * @param id
     * @return
     */
    public Map<String, List<ResourceModel>> selectResourceByStoreId(int id) {
        ResourceExample resourceExample = new ResourceExample();
        resourceExample.or().andParentIdEqualTo(id).andParentTypeEqualTo("1").andResKeyEqualTo("store_category").andResTypeEqualTo("1");
        List<Resource> resources = resourceMapper.selectByExample(resourceExample);
        Map<String, List<ResourceModel>> resourceMap = new HashMap<String, List<ResourceModel>>();
        if (resources != null && resources.size() > 0) {
            List<ResourceModel> resourceModels = new ArrayList<ResourceModel>();
            for (Resource resource : resources) {
//                String key = resource.getResKey();
//                if (resourceMap.containsKey(key)) {
//                    resourceModels = resourceMap.get(key);
//                } else {
//                    resourceModels = Lists.newArrayList();
//                }
                ResourceModel courseImageModel = new ResourceModel();
                courseImageModel.setId(resource.getId());
                courseImageModel.setLink(resource.getLink());
                courseImageModel.setUrl(resource.getUrl());
                courseImageModel.setTitle(resource.getTitle());
                resourceModels.add(courseImageModel);
                resourceMap.put("top_banner", resourceModels);
            }
        }
        return resourceMap;
    }

    /**
     * 根据店面id查询课程
     *
     * @param id
     * @return
     */
    public List<StoreCourseModel> selectCourseInfoByStoreId(int id) {
        List<StoreCourseModel> courses = Lists.newArrayList();
        List<CourseInfo> courseInfos = courseInfoMapper.selectByStoreId(id);
        courseInfos = courseInfoMapper.queryLatestTeamCourseByStoreId(id);
        if (courseInfos != null && courseInfos.size() > 0) {
            for (CourseInfo courseInfo : courseInfos) {
            	
            	ResourceExample resourceExample = new ResourceExample();
            	resourceExample.or().andParentIdEqualTo(courseInfo.getId()).andParentTypeEqualTo("2").andResKeyLike("%category%");
            	List<Resource> resources = resourceMapper.selectByExample(resourceExample);
            	Resource resource=null;
            	if(resources!=null && resources.size()>0){
            		 resource =	resources.get(0);
            	}
            	
                StoreCourseModel storeCourseModel = new StoreCourseModel();
                storeCourseModel.setTitle(courseInfo.getTitle());
                storeCourseModel.setCourseId(courseInfo.getId());
                String courseType = courseInfo.getCourseType();
                //课程类型与订单类型转换 EarvinWoo
                String orderType="0";
                if("1".equals(courseType)){
                	orderType="2";
                }else if("2".equals(courseType)){
                	orderType="1";
                }else if("3".equals(courseType)){
                	orderType="3";
                }
                storeCourseModel.setOrderType(orderType);
                if(resource!=null){
                	storeCourseModel.setHeadImg(resource.getUrl());
                }
                courses.add(storeCourseModel);
            }
        }
        return courses;
    }

    /**
     * 查询店面资源信息
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, List<StoreResourceModel>> queryResourceByStoreId(int id) throws Exception {
//        ResourceExample resourceExample = new ResourceExample();
//        resourceExample.or().andParentIdEqualTo(id).andParentTypeEqualTo("1").andResTypeEqualTo("2");
//        resourceExample.or().andParentIdEqualTo(id).andParentTypeEqualTo("1");
//        List<Resource> resources = resourceMapper.queryResourceByStoreId(id);
//
        Map<String, List<StoreResourceModel>> videosMap = new HashMap<>();
//        if (resources != null && resources.size() > 0) {
//            List<StoreResourceModel> videos = null;
//            for (Resource resource : resources) {
//                String resKey = resource.getResKey();
//                if (videosMap.containsKey(resKey)) {
//                    videos = videosMap.get(resKey);
//                } else {
//                    videos = Lists.newArrayList();
//                }
//                StoreResourceModel storeResourceModel = new StoreResourceModel();
//                storeResourceModel.setTitle(resource.getTitle());
//                storeResourceModel.setLink(resource.getLink());
//                storeResourceModel.setId(resource.getId());
//                storeResourceModel.setUrl(resource.getUrl());
//                videos.add(storeResourceModel);
//                videosMap.put(resKey, videos);
//            }
//        }
        return videosMap;
    }

    /**
     * 进店模式资源查询
     * @return
     */
    @Override
    public Map<String, Object> enterStoreResourceList(){

        Map<String, Object> resultMap = new HashMap<>();

        List<InStore> instore_list = operativeMapper.queryInStoreList();//进店轮播图
        resultMap.put("banner_img", instore_list.size()>0? instore_list.get(0):instore_list);

        List<JsRSVideoInfo> jsrsvideo_list = operativeMapper.queryJsrfVideoList();//健身视频
        resultMap.put("jsrsvideo", jsrsvideo_list.size()>0? jsrsvideo_list.get(0):jsrsvideo_list );

        List<JsRSVideoInfo> sfsxvideo_list = operativeMapper.querySfsxVideoList();//瘦身塑形
        resultMap.put("sfsxvideo", sfsxvideo_list.size()>0? sfsxvideo_list.get(0):sfsxvideo_list);

        List<JsRSVideoInfo> wypbvideo_list = operativeMapper.queryWypbVideoList();//我要跑步
        resultMap.put("wypbvideo", wypbvideo_list.size() >0? wypbvideo_list.get(0):wypbvideo_list);

        List<JsRSVideoInfo> wymjxvideo_list = operativeMapper.queryWymjxVideoList();//我要马甲线
        resultMap.put("wymjxvideo", wymjxvideo_list.size()>0? wymjxvideo_list.get(0):wymjxvideo_list);

        List<JsRSVideoInfo> wymtbvideo_list = operativeMapper.queryWymtbVideoList();//我要蜜桃臂
        resultMap.put("wymtbvideo", wymtbvideo_list.size() >0?wymtbvideo_list.get(0):wymtbvideo_list);

        return resultMap;

    }
//
//    /**
//     * 查询所有正常状态门店 旧方法 下次更新后删除
//     * @param longitudeLatitude
//     * @return
//     */
//    @Override
//    public List<StoreListResultModel> queryAllStore2(String longitudeLatitude) {
//        List<StoreListResultModel> listResultModels = Lists.newArrayList();
//        StoreInfoExample storeInfoExample = new StoreInfoExample();
//        storeInfoExample.or().andStatusEqualTo("1");//查询即将开业
//        storeInfoExample.or().andStatusEqualTo("2");//AND开业状态的门店
//        List<StoreInfo> storeInfoList = storeInfoMapper.selectByExample(storeInfoExample);
//        if (storeInfoList != null && storeInfoList.size() > 0) {
//            for (StoreInfo storeInfo : storeInfoList) {
//                StoreListResultModel storeListResultModel = new StoreListResultModel();
//                storeListResultModel.setAddressLink(storeInfo.getAddressLink());
//                storeListResultModel.setStoreAddress(storeInfo.getAddress());
//                storeListResultModel.setStoreName(storeInfo.getStoreName());
//                storeListResultModel.setId(storeInfo.getId());
//                storeListResultModel.setStatus(storeInfo.getStatus());
//                if (StringUtils.isNotBlank(longitudeLatitude) && (!"undefined".equals(longitudeLatitude))) {
//                    storeListResultModel.setDistance(String.valueOf(
//                            DistanceUtil.GetDistance(storeInfo.getLongitude().doubleValue(), storeInfo.getLatitude().doubleValue(), Double.valueOf(longitudeLatitude.split(",")[1]), Double.valueOf(longitudeLatitude.split(",")[0]))));
//                    storeListResultModel.setDistance(storeListResultModel.getDistance().substring(0, storeListResultModel.getDistance().lastIndexOf(".")));
//                }else if("undefined".equals(longitudeLatitude)){
//                	storeListResultModel.setDistance("0");
//                }
//                Map<String, List<ResourceModel>> resourceMap = selectResourceByStoreId(storeInfo.getId());
//                if (resourceMap != null && resourceMap.size() > 0) {
//                    if (resourceMap.containsKey("top_banner")) {
//                        List<ResourceModel> resourceModels = resourceMap.get("top_banner");
//                        if (resourceModels != null && resourceModels.size() > 0) {
//                            ResourceModel rm = resourceModels.get(0);
//                            storeListResultModel.setPreviewUrl(rm.getUrl());
//                        }
//                    }
//                }
//                listResultModels.add(storeListResultModel);
//            }
//        }
//        return listResultModels;
//
//    }

    /**
     * 查询所有正常状态门店 blank
     * @param pageIndex 页码
     * @param pageSize 页面大小
     * @param longitudeLatitude 经纬度
     * @return
     */
    @Override
    public ApiResultModel queryAllStore(Integer pageIndex, Integer pageSize, String longitudeLatitude,String cityId,String districtId, Integer userId){

        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<>();
        Map<String, Object> params = new HashMap();
        params.put("pageIndex", pageIndex * pageSize);
        params.put("pageSize", pageSize);
        if(StringUtils.isNotBlank(longitudeLatitude) && longitudeLatitude.split(",").length == 2){
            params.put("latitude", longitudeLatitude.split(",")[0]);
            params.put("longitude", longitudeLatitude.split(",")[1]);
        }
        if(cityId !=null){
        	params.put("cityId", cityId);	
        }
        if(districtId !=null){
        	params.put("districtId", districtId);
        }
        if(userId != null) {
        	params.put("userId", userId);
        }
        Map<String, Object> map = new HashMap<>();
        List<StoreResultModel> list = storeInfoMapper.queryAllStore(params);
        map.put("list", list);
        map.put("count", storeInfoMapper.queryAllStoreCount(params));
        map.put("top_banner", queryStoreMainPageResource());
        map.put("area_info",storeInfoMapper.queryCityAreaResultForStoreInfo());

        apiResultModel.setData(map);
        apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
        return apiResultModel;
    }



    @Override
    public List<ResourceModel> queryStoreMainPageResource() {
        List<ResourceModel> resourceModels = Lists.newArrayList();
        ResourceExample resourceExample = new ResourceExample();
        resourceExample.or().andParentTypeEqualTo("1").andResKeyEqualTo("lemonshop_banner");//门店首页图片
        List<Resource> resources = resourceMapper.selectByExample(resourceExample);
        if (resources != null && resources.size() > 0) {
            for (Resource resource : resources) {
                ResourceModel resourceModel = new ResourceModel();
                resourceModel.setUrl(resource.getUrl());
                resourceModel.setId(resource.getId());
                resourceModel.setLink(resource.getLink());
                resource.setTitle(resource.getTitle());
                resourceModels.add(resourceModel);
            }
            return resourceModels;
        }
        return null;
    }


    /**
     *
     * 查询所有在线门店
     * @return
     */
    @Override
    public List<StoreInfo> queryAllStoreList() {
        return storeInfoMapper.queryAllStoreList();
    }
    
    /**
    *
    *根据课程查询对应的门店
    * @return
    */
   @Override
   public List<StoreInfo> queryStoreListByCourseId(Integer courseId) {
       return storeInfoMapper.queryStoreListByCourseId(courseId);
   }
}
